<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产分类" prop="cate_id">
          <treeselect v-model="queryParams.cate_id" :options="cateOptions" style="width:180px"
          :normalizer="normalizer" placeholder="请选择资产分类" />
      </el-form-item>
      <el-form-item label="资产编号" prop="nums">
        <el-input
          v-model="queryParams.nums"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核结果" prop="check_status">
        <el-select v-model="queryParams.check_status" placeholder="请选择审核结果" clearable>
          <el-option
            v-for="dict in dict.type.flow_check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="apply_time">
       <el-date-picker
          v-model="queryParams.apply_time"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['asset:use:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['asset:use:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="useList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类" align="center" prop="cate_name" />
      <el-table-column label="型号" align="center" prop="model_name" />
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="申请原由" align="center" prop="reason" />
      <el-table-column label="审核结果" align="center" prop="check_status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.flow_check_status" :value="scope.row.check_status"/>
        </template>
      </el-table-column>
      <el-table-column label="资产编号" align="center" prop="nums" />
      <el-table-column label="接收时间" align="center" prop="recv_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recv_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="apply_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.apply_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.apply_status != '1'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button v-if="scope.row.apply_status == '1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:use:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.apply_status == '1'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleApply(scope.row)"
            v-hasPermi="['asset:purchase:edit']"
          >提交</el-button>
          <el-button v-if="scope.row.apply_status == '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['asset:use:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />
    <!-- 添加或修改使用申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="form.apply_status != '1'">
         <el-form-item label="资产分类" prop="cate_id">
            <treeselect v-model="form.cate_id" :options="cateOptions" :normalizer="normalizer" placeholder="请选择资产分类" />
        </el-form-item>
        <el-form-item label="型号" prop="model_id">
          <el-select v-model="form.model_id" placeholder="请选择型号" clearable>
            <el-option
                v-for="v in formModelOptions"
                :key="v.value"
                :label="v.label"
                :value="v.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="申请原由" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入申请原由" />
        </el-form-item>
        <el-form-item label="申请说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入申请说明" />
        </el-form-item>
        <el-form-item label="审核结果" prop="check_status" v-if="form.id">
          <el-radio-group v-model="form.check_status">
            <el-radio
              v-for="dict in dict.type.flow_check_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资产编号" prop="nums" v-if="form.id">
          <el-input v-model="form.nums" placeholder="请输入资产编号" />
        </el-form-item>
        <el-form-item label="接收时间" prop="recv_time" v-if="form.recv_time">
            <el-input v-model="form.recv_time" readonly />
        </el-form-item>
        <el-form-item label="申请时间" prop="apply_time" v-if="form.id">
            <el-input v-model="form.apply_time" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <apply-dialog :applyData="apply" model="asset_use" @cancel="applyCancel" @success="applySuccess" />
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";
import ApplyDialog from "@/components/ApplyDialog";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "MyUse",
  components: {
    ApplyDialog, Treeselect
  },
  dicts: ['flow_check_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 使用申请表格数据
      useList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        cate_id: null,
        model_id: null,
        amount: null,
        dept_id: null,
        user_id: null,
        reason: null,
        check_status: null,
        imgs: null,
        nums: null,
        recv_time: null,
        apply_time: [],
        "@alias": "t",
        "@exp": {
            nums: 'lk',
            apply_time: 'bt'
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      // 导入参数
      upload: false,
      // 表单参数
      form: {},
      userOptions: [],
      deptOptions: [],
      cateOptions: [],
      modelOptions: [],
      apply: null,
      // 表单校验
      rules: {
        cate_id: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        model_id: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "申请原由不能为空", trigger: "blur" }
        ],
        apply_time: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    apiDs('asset_model_select').then(response=>{
        this.modelOptions = response.data;
    });
    apiDs('asset_category_select').then(response=>{
        this.cateOptions = this.handleTree(response.data, "value", "pid");
    });
  },
  computed: {
    formModelOptions: function () {
      let options = [];
      if(this.form.cate_id == null){
        return options;
      }
      for(var i=0;i<this.modelOptions.length;i++){
        if(this.modelOptions[i].cate_id == this.form.cate_id){
          options.push(this.modelOptions[i]);
        }
      }
      console.log(options)
      return options;
    },    
    searchModelOptions: function () {
      let options = [];
      if(this.form.cate_id == null){
        return options;
      }
      for(var i=0;i<this.modelOptions.length;i++){
        if(this.modelOptions[i].cate_id == this.queryParams.cate_id){
          options.push(this.modelOptions[i]);
        }
      }
      return options;
    }
  },
  methods: {
    /** 查询使用申请列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['asset_use'] = {...this.queryParams};
      if(this.queryParams.apply_time.length == 0){
        params['asset_use']['apply_time'] = null;
      }
      params['@pager'] = this.pager;
      params['asset_model'] = {
          "@alias": "m",
          "@join": "m.id = t.model_id",
          "@column":"name model_name"
      };
      params['asset_category'] = {
          "@alias": "c",
          "@join": "c.id = t.cate_id",
          "@column":"name cate_name"
      };
      apiGet(params).then(response => {
        this.useList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 转换资产分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cate_id: null,
        model_id: null,
        amount: null,
        dept_id: "@orgId()",
        user_id: "@userId()",
        reason: null,
        remark: null,
        check_status: null,
        apply_status: '1',
        nums: null,
        recv_time: null,
        apply_time: "@now()"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加使用申请";
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['asset_use'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "使用申请详细";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['asset_use'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改使用申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            let data = {};
            data['asset_use'] = this.form;
            data['@tags'] = ['asset_use'];
          if (this.form.id != null) {
            apiPut(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiPost(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的使用申请数据？').then(function() {
        let data = {};
        data['asset_use'] = { id:ids, "@exp":{id:"in"}};
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
        let params = {};
      params['asset_use'] = this.queryParams;
      params['@pager'] = {page:1, limit:10000};
      apiExport(params).then(response => {
        apiDownload(response.msg);
      });
    },
    /** 审批按钮操作 */
    handleApply(row) {
      this.apply = {
        "id":row.id,
        "user_id": row.user_id,
        "user_name": row.user_name,
        reason: row.reason,
        "dept_id": row.dept_id,
        "title": "使用申请",
        "num": this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')+'2'+Math.ceil(Math.random()*10)
      }
    },
    applySuccess(msg) {
        let data = {
            asset_use: {
                id: this.apply.id,
                apply_time: "@now()",
                apply_status:"2",
                check_status:"1"
            },
            "@tags": ['asset_use']
         };
        apiPut(data).then(response => {
            this.getList();
        });
        this.apply = null;
    },
    applyCancel() {
        this.apply = null;
    }
  }
};
</script>
